package org.chris.quick.widgets

import android.content.Context
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.view.ViewPager
import android.util.AttributeSet

import org.chris.quick.b.BaseFragmentPagerAdapter

/**
 * Created by zoulx on 2017/11/14.
 */

class TabFragmentViewPager : ViewPager {
    var tabAdapter: Adapter? = null

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    fun setData(fm: FragmentManager, vararg fragments: Fragment): Unit = if (tabAdapter == null) {
        tabAdapter = Adapter(fm, *fragments)
        adapter = tabAdapter
    } else {
        tabAdapter!!.setDataList(fragments as Array<Fragment>)
    }

    fun setupBottomNavigationView(bottomNavigationView: BottomNavigationView) {
        addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                bottomNavigationView.selectedItemId = bottomNavigationView.menu.getItem(position).itemId
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
    }

    class Adapter(fm: FragmentManager, vararg fragments: Fragment) : BaseFragmentPagerAdapter(fm) {
        private var dataList: Array<Fragment>? = null

        init {
            this.dataList = fragments as Array<Fragment>
        }

        fun setDataList(dataList: Array<Fragment>) {
            this.dataList = dataList
            notifyDataSetChanged()
        }

        override fun getItem(position: Int): Fragment = dataList!![position]

        override fun getCount(): Int = if (dataList == null) 0 else dataList!!.size
    }
}